<template>
  <div class="statistics">
    <div class="stats-header">
      <h2>📊 系统统计</h2>
      <button @click="loadStats" class="btn btn-secondary">🔄 刷新数据</button>
    </div>
    
    <div v-if="!loading">
      <!-- 总览卡片 -->
      <div class="overview-section">
        <h3>系统概览</h3>
        <div class="stats-grid">
          <div class="stat-card primary">
            <div class="stat-icon">👥</div>
            <div class="stat-content">
              <div class="stat-value">{{ stats.users?.total || 0 }}</div>
              <div class="stat-label">总用户数</div>
              <div class="stat-meta">
                活跃: {{ stats.users?.active || 0 }} | 
                禁用: {{ stats.users?.disabled || 0 }}
              </div>
            </div>
          </div>
          
          <div class="stat-card success">
            <div class="stat-icon">🔑</div>
            <div class="stat-content">
              <div class="stat-value">{{ stats.tokens?.total || 0 }}</div>
              <div class="stat-label">总令牌数</div>
              <div class="stat-meta">
                平均: {{ stats.tokens?.avgPerUser || 0 }} 个/用户
              </div>
            </div>
          </div>
          
          <div class="stat-card info">
            <div class="stat-icon">👑</div>
            <div class="stat-content">
              <div class="stat-value">{{ stats.users?.admins || 0 }}</div>
              <div class="stat-label">管理员</div>
              <div class="stat-meta">
                占比: {{ adminPercentage }}%
              </div>
            </div>
          </div>
          
          <div class="stat-card warning">
            <div class="stat-icon">📝</div>
            <div class="stat-content">
              <div class="stat-value">{{ stats.logs?.total || 0 }}</div>
              <div class="stat-label">审计日志</div>
              <div class="stat-meta">
                今日: {{ stats.logs?.today || 0 }}
              </div>
            </div>
          </div>
        </div>
      </div>
      
      <!-- 用户统计 -->
      <div class="section">
        <h3>👥 用户统计</h3>
        <div class="info-grid">
          <div class="info-item">
            <span class="info-label">今日新增</span>
            <span class="info-value highlight-success">+{{ stats.users?.newToday || 0 }}</span>
          </div>
          <div class="info-item">
            <span class="info-label">本周新增</span>
            <span class="info-value">+{{ stats.users?.newThisWeek || 0 }}</span>
          </div>
          <div class="info-item">
            <span class="info-label">本月新增</span>
            <span class="info-value">+{{ stats.users?.newThisMonth || 0 }}</span>
          </div>
          <div class="info-item">
            <span class="info-label">活跃用户</span>
            <span class="info-value highlight-info">{{ stats.users?.active || 0 }}</span>
          </div>
          <div class="info-item">
            <span class="info-label">今日活跃</span>
            <span class="info-value">{{ stats.users?.activeToday || 0 }}</span>
          </div>
          <div class="info-item">
            <span class="info-label">本周活跃</span>
            <span class="info-value">{{ stats.users?.activeThisWeek || 0 }}</span>
          </div>
        </div>
      </div>
      
      <!-- 令牌统计 -->
      <div class="section">
        <h3>🔑 令牌统计</h3>
        <div class="info-grid">
          <div class="info-item">
            <span class="info-label">今日新增</span>
            <span class="info-value highlight-success">+{{ stats.tokens?.newToday || 0 }}</span>
          </div>
          <div class="info-item">
            <span class="info-label">本周新增</span>
            <span class="info-value">+{{ stats.tokens?.newThisWeek || 0 }}</span>
          </div>
          <div class="info-item">
            <span class="info-label">本月新增</span>
            <span class="info-value">+{{ stats.tokens?.newThisMonth || 0 }}</span>
          </div>
          <div class="info-item">
            <span class="info-label">收藏数量</span>
            <span class="info-value highlight-warning">⭐ {{ stats.tokens?.favorites || 0 }}</span>
          </div>
          <div class="info-item">
            <span class="info-label">今日使用</span>
            <span class="info-value">{{ stats.tokens?.usedToday || 0 }}</span>
          </div>
          <div class="info-item">
            <span class="info-label">总使用次数</span>
            <span class="info-value">{{ stats.tokens?.totalUsage || 0 }}</span>
          </div>
        </div>
      </div>
      
      <!-- 热门服务 -->
      <div class="section">
        <h3>🔥 热门服务 TOP 10</h3>
        <div class="top-services">
          <div 
            v-for="(service, index) in stats.topServices?.slice(0, 10) || []" 
            :key="service.name"
            class="service-item"
          >
            <div class="service-rank">{{ index + 1 }}</div>
            <div class="service-info">
              <div class="service-name">{{ service.name }}</div>
              <div class="service-bar">
                <div 
                  class="service-bar-fill" 
                  :style="{ width: getServicePercentage(service.count) + '%' }"
                ></div>
              </div>
            </div>
            <div class="service-count">{{ service.count }} 个</div>
          </div>
          
          <div v-if="!stats.topServices || stats.topServices.length === 0" class="empty-state">
            暂无数据
          </div>
        </div>
      </div>
      
      <!-- 活动统计 -->
      <div class="section">
        <h3>📈 活动统计</h3>
        <div class="info-grid">
          <div class="info-item">
            <span class="info-label">今日登录次数</span>
            <span class="info-value">{{ stats.activities?.loginsToday || 0 }}</span>
          </div>
          <div class="info-item">
            <span class="info-label">今日验证码生成</span>
            <span class="info-value">{{ stats.activities?.codesGeneratedToday || 0 }}</span>
          </div>
          <div class="info-item">
            <span class="info-label">本周登录次数</span>
            <span class="info-value">{{ stats.activities?.loginsThisWeek || 0 }}</span>
          </div>
          <div class="info-item">
            <span class="info-label">活跃会话数</span>
            <span class="info-value highlight-info">{{ stats.activities?.activeSessions || 0 }}</span>
          </div>
          <div class="info-item">
            <span class="info-label">平均会话时长</span>
            <span class="info-value">{{ stats.activities?.avgSessionDuration || 0 }} 分钟</span>
          </div>
          <div class="info-item">
            <span class="info-label">峰值在线数</span>
            <span class="info-value">{{ stats.activities?.peakOnline || 0 }}</span>
          </div>
        </div>
      </div>
      
      <!-- 系统信息 -->
      <div class="section">
        <h3>💻 系统信息</h3>
        <div class="system-info">
          <div class="info-row">
            <span class="info-label">数据库大小</span>
            <span class="info-value">{{ formatSize(stats.system?.dbSize) }}</span>
          </div>
          <div class="info-row">
            <span class="info-label">系统启动时间</span>
            <span class="info-value">{{ formatDate(stats.system?.startTime) }}</span>
          </div>
          <div class="info-row">
            <span class="info-label">运行时间</span>
            <span class="info-value">{{ formatUptime(stats.system?.uptime) }}</span>
          </div>
          <div class="info-row">
            <span class="info-label">Node.js 版本</span>
            <span class="info-value">{{ stats.system?.nodeVersion || '-' }}</span>
          </div>
          <div class="info-row">
            <span class="info-label">API 版本</span>
            <span class="info-value">v{{ stats.system?.apiVersion || '1.0.0' }}</span>
          </div>
        </div>
      </div>
    </div>
    
    <div v-else class="loading">
      <div class="spinner"></div>
      <p>加载统计数据中...</p>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue';
import api from '@/api';

const loading = ref(false);
const stats = ref({});

const adminPercentage = computed(() => {
  const total = stats.value.users?.total || 0;
  const admins = stats.value.users?.admins || 0;
  return total > 0 ? Math.round((admins / total) * 100) : 0;
});

function getServicePercentage(count) {
  const max = stats.value.topServices?.[0]?.count || 1;
  return (count / max) * 100;
}

function formatDate(dateString) {
  if (!dateString) return '-';
  const date = new Date(dateString);
  return date.toLocaleString('zh-CN');
}

function formatSize(bytes) {
  if (!bytes) return '-';
  const sizes = ['B', 'KB', 'MB', 'GB'];
  const i = Math.floor(Math.log(bytes) / Math.log(1024));
  return Math.round(bytes / Math.pow(1024, i) * 100) / 100 + ' ' + sizes[i];
}

function formatUptime(seconds) {
  if (!seconds) return '-';
  const days = Math.floor(seconds / 86400);
  const hours = Math.floor((seconds % 86400) / 3600);
  const minutes = Math.floor((seconds % 3600) / 60);
  
  if (days > 0) return `${days}天 ${hours}小时`;
  if (hours > 0) return `${hours}小时 ${minutes}分钟`;
  return `${minutes}分钟`;
}

async function loadStats() {
  loading.value = true;
  try {
    const response = await api.get('/admin/stats');
    stats.value = response.data.data || {};
  } catch (error) {
    console.error('加载统计数据失败:', error);
    alert('加载统计数据失败');
  } finally {
    loading.value = false;
  }
}

onMounted(() => {
  loadStats();
});
</script>

<style scoped>
.statistics {
  background: var(--bg-color, #fff);
  border-radius: 12px;
  padding: 30px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.stats-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30px;
}

.stats-header h2 {
  font-size: 24px;
  color: var(--text-color, #333);
  margin: 0;
}

.btn {
  padding: 10px 20px;
  border: none;
  border-radius: 8px;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.2s;
}

.btn-secondary {
  background: var(--bg-secondary, #f3f4f6);
  color: var(--text-color, #333);
}

.btn-secondary:hover {
  background: var(--border-color, #e5e7eb);
}

.overview-section {
  margin-bottom: 32px;
}

.overview-section h3 {
  font-size: 18px;
  color: var(--text-color, #333);
  margin-bottom: 16px;
}

.stats-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: 20px;
  margin-bottom: 32px;
}

.stat-card {
  display: flex;
  gap: 16px;
  padding: 24px;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  transition: transform 0.2s;
}

.stat-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.15);
}

.stat-card.primary {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
}

.stat-card.success {
  background: linear-gradient(135deg, #10b981 0%, #059669 100%);
  color: white;
}

.stat-card.info {
  background: linear-gradient(135deg, #3b82f6 0%, #2563eb 100%);
  color: white;
}

.stat-card.warning {
  background: linear-gradient(135deg, #f59e0b 0%, #d97706 100%);
  color: white;
}

.stat-icon {
  font-size: 48px;
  opacity: 0.9;
}

.stat-content {
  flex: 1;
}

.stat-value {
  font-size: 36px;
  font-weight: bold;
  line-height: 1.2;
  margin-bottom: 4px;
}

.stat-label {
  font-size: 14px;
  opacity: 0.9;
  margin-bottom: 8px;
}

.stat-meta {
  font-size: 13px;
  opacity: 0.8;
}

.section {
  margin-bottom: 32px;
}

.section h3 {
  font-size: 18px;
  color: var(--text-color, #333);
  margin-bottom: 16px;
}

.info-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 16px;
}

.info-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px;
  background: var(--bg-secondary, #f9fafb);
  border-radius: 8px;
  border-left: 3px solid var(--border-color, #e5e7eb);
}

.info-label {
  font-size: 14px;
  color: var(--text-secondary, #6b7280);
}

.info-value {
  font-size: 20px;
  font-weight: bold;
  color: var(--text-color, #333);
}

.highlight-success {
  color: #10b981;
}

.highlight-info {
  color: #3b82f6;
}

.highlight-warning {
  color: #f59e0b;
}

.top-services {
  background: var(--bg-secondary, #f9fafb);
  border-radius: 8px;
  padding: 20px;
}

.service-item {
  display: flex;
  align-items: center;
  gap: 16px;
  padding: 12px 0;
  border-bottom: 1px solid var(--border-color, #e5e7eb);
}

.service-item:last-child {
  border-bottom: none;
}

.service-rank {
  width: 32px;
  height: 32px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: var(--primary-color, #3b82f6);
  color: white;
  border-radius: 50%;
  font-weight: bold;
  font-size: 14px;
}

.service-info {
  flex: 1;
}

.service-name {
  font-weight: 500;
  color: var(--text-color, #333);
  margin-bottom: 6px;
}

.service-bar {
  width: 100%;
  height: 6px;
  background: var(--border-color, #e5e7eb);
  border-radius: 3px;
  overflow: hidden;
}

.service-bar-fill {
  height: 100%;
  background: var(--primary-color, #3b82f6);
  transition: width 0.3s;
}

.service-count {
  font-weight: 600;
  color: var(--text-secondary, #6b7280);
}

.system-info {
  background: var(--bg-secondary, #f9fafb);
  border-radius: 8px;
  overflow: hidden;
}

.info-row {
  display: flex;
  justify-content: space-between;
  padding: 16px 20px;
  border-bottom: 1px solid var(--border-color, #e5e7eb);
}

.info-row:last-child {
  border-bottom: none;
}

.info-row .info-label {
  font-weight: 500;
}

.empty-state {
  text-align: center;
  padding: 40px 20px;
  color: var(--text-secondary, #6b7280);
}

.loading {
  text-align: center;
  padding: 80px 20px;
}

.spinner {
  width: 40px;
  height: 40px;
  margin: 0 auto 16px;
  border: 4px solid var(--bg-secondary, #f3f4f6);
  border-top-color: var(--primary-color, #3b82f6);
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  to {
    transform: rotate(360deg);
  }
}

.loading p {
  color: var(--text-secondary, #6b7280);
}

/* 深色模式 */
.dark-theme .statistics {
  background: #1f2937;
}

.dark-theme .info-item,
.dark-theme .top-services,
.dark-theme .system-info {
  background: #111827;
}

.dark-theme .info-row {
  border-bottom-color: #374151;
}

.dark-theme .service-item {
  border-bottom-color: #374151;
}

.dark-theme .service-bar {
  background: #374151;
}

/* 响应式 */
@media (max-width: 768px) {
  .stats-grid {
    grid-template-columns: 1fr;
  }
  
  .info-grid {
    grid-template-columns: 1fr;
  }
  
  .stat-icon {
    font-size: 36px;
  }
  
  .stat-value {
    font-size: 28px;
  }
}
</style>


